//
//  Navigator.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/8/23.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation


class Navigator {
    
    //导航软件item
    struct NavigatorItem {
        let name: String
        let index: Int
    }

    //是否安装了这个平台
    static func install(_ string: String) -> Bool {
        if let url = URL(string: string) {
            return UIApplication.shared.canOpenURL(url)
        }
        return false
    }
    
    //返回所有已经安装的平台数组
    static func installApps() ->[NavigatorItem] {
        var apps = [NavigatorItem]()
        if install("baidumap://") {
            
            let BaiduApp = NavigatorItem(name: "百度地图", index: 0)
            apps.append(BaiduApp)
            
        }
        if install("iosamap://") {
            
            let BaiduApp = NavigatorItem(name: "高德地图", index: 1)
            apps.append(BaiduApp)
        }
        
        let systemApp = NavigatorItem(name: "苹果地图", index: 2)
        apps.append(systemApp)
        return apps
    }
    
    static func getBaiDuCoordinateByGaoDe(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        
        let PI = 3.14159265358979324 * 3000.0 / 180.0
        let x = coordinate.longitude, y = coordinate.latitude
        let z = sqrt(x * x + y * y) +  0.00002 * sin(y * PI)
        let theta = atan2(y, x) + 0.000003 * cos(x * PI)
        return CLLocationCoordinate2DMake(z * sin(theta) + 0.006,z * cos(theta) + 0.0065)
    }
    //跳转到高德地图
    static func gotoGaodeApp(_ lat: Double,lon: Double) {
        
        let str = "iosamap://navi?sourceApplication=ssss&backScheme=timerent.9zcap.com&lat=\(lat)&lon=\(lon)&dev=0&style=2"
        let url = URL(string: str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        if let temp = url {
            UIApplication.shared.open( temp, options: [:], completionHandler: nil)
        }
    }
    //跳转到百度地图
    static func gotoBaiduApp(_ lat: Double,lon: Double) {
        let coordinate = self.getBaiDuCoordinateByGaoDe(coordinate: CLLocationCoordinate2DMake(lat, lon))
        let str = "baidumap://map/direction?origin=&destination=latlng:\(coordinate.latitude),\(coordinate.longitude)|name=ssss&mode=walking"
        let url = URL(string: str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        if let temp = url {
            UIApplication.shared.open( temp, options: [:], completionHandler: nil)
        }
    }
    //跳转到苹果地图
    static func gotoSystemMap(_ lat: Double,lon: Double) {
        let loc = CLLocationCoordinate2DMake(lat, lon)
        let currentLocation = MKMapItem.forCurrentLocation()
        let toLocation = MKMapItem(placemark: MKPlacemark(coordinate: loc, addressDictionary: nil))
        MKMapItem.openMaps(with: [currentLocation,toLocation], launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: "true"])
    }
}
